package fudan.se.project.util.entitymanage;


import fudan.se.project.domain.User;
import fudan.se.project.domain.sysrole.SystemAuthority;
import fudan.se.project.util.repository.RepositoryUtil;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.Collections;
import java.util.HashSet;

public class UserManagementUtil extends EntityManagementUtil {

    private final RepositoryUtil repositoryUtil;
    private final PasswordEncoder encoder = new BCryptPasswordEncoder();

    public UserManagementUtil(RepositoryUtil repositoryUtil) {
        this.repositoryUtil = repositoryUtil;
    }

    public User createNewUser(String username) {
        User user = new User(username, username, encoder.encode(username),
                qqMail(username), username, username);
        user.setSystemAuthorities(new HashSet<>(Collections.singletonList(
                repositoryUtil.systemAuthorityRepository.findByAuthority(SystemAuthority.Authority.USER))));
        user = repositoryUtil.userRepository.save(user);
        return user;
    }

    public User queryUser(String username) {
        return repositoryUtil.userRepository.findByUsername(username);
    }


}
